package controllers

import (
	"bankend/services"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"bankend/database"
	"bankend/models"

	"github.com/gin-gonic/gin"
)

// GetMessageTemplates 根据查询参数模糊搜索消息模板（只返回未软删除记录）
// GET /api/message_templates?q=关键词
func GetMessageTemplates(c *gin.Context) {
	query := c.Query("q")
	var templates []models.MessageTemplate
	db := database.DB
	if query != "" {
		pattern := "%" + strings.TrimSpace(query) + "%"
		db.Where("deleted_at IS NULL").
			Where("title LIKE ? OR content LIKE ?", pattern, pattern).
			Find(&templates)
	} else {
		db.Where("deleted_at IS NULL").Find(&templates)
	}
	c.JSON(http.StatusOK, gin.H{"templates": templates})
}

// GetMessageTemplate 根据 ID 获取单个消息模板
// GET /api/message_templates/:id
func GetMessageTemplate(c *gin.Context) {
	idParam := c.Param("id")
	id, err := strconv.Atoi(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的模板ID"})
		return
	}
	var template models.MessageTemplate
	if err := database.DB.Where("template_id = ? AND deleted_at IS NULL", id).First(&template).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "模板不存在"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"template": template})
}

// CreateMessageTemplate 创建新的消息模板
// POST /api/message_templates
func CreateMessageTemplate(c *gin.Context) {
	var template models.MessageTemplate
	if err := c.ShouldBindJSON(&template); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	template.CreateTime = time.Now()
	template.UpdateTime = time.Now()
	if err := database.DB.Create(&template).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusCreated, gin.H{"template": template})
}

// UpdateMessageTemplate 更新消息模板
// PUT /api/message_templates/:id
func UpdateMessageTemplate(c *gin.Context) {
	idParam := c.Param("id")
	id, err := strconv.Atoi(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的模板ID"})
		return
	}
	var template models.MessageTemplate
	if err := database.DB.Where("template_id = ? AND deleted_at IS NULL", id).First(&template).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "模板不存在"})
		return
	}
	var updated models.MessageTemplate
	if err := c.ShouldBindJSON(&updated); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	updated.ID = template.ID
	updated.CreateTime = template.CreateTime
	updated.UpdateTime = time.Now()
	if err := database.DB.Model(&template).Updates(updated).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"template": template})
}

// DeleteMessageTemplate 软删除消息模板
// DELETE /api/message_templates/:id
func DeleteMessageTemplate(c *gin.Context) {
	idParam := c.Param("id")
	id, err := strconv.Atoi(idParam)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的模板ID"})
		return
	}
	now := time.Now()
	if err := database.DB.Model(&models.MessageTemplate{}).
		Where("template_id = ? AND deleted_at IS NULL", id).
		Update("deleted_at", now).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "模板已软删除"})
}

// PushMessageTemplate 定向推送接口：根据模板ID和目标用户（按角色或指定用户ID列表）进行推送
// POST /api/message_templates/push
// controllers/message_template.go
func PushMessageTemplate(c *gin.Context) {
	// 1. 绑定请求体
	var req struct {
		WeChatTplID string `json:"wechat_tpl_id"`
		Role        string `json:"role"`
		UserIDs     []int  `json:"user_ids"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		log.Printf("[Push] 绑定请求体失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	log.Printf("[Push] 收到推送请求: wechat_tpl_id=%q, role=%q, user_ids=%v",
		req.WeChatTplID, req.Role, req.UserIDs)

	// 2. 查询模板
	var tpl models.MessageTemplate
	if err := database.DB.
		Where("wechat_tpl_id = ? AND deleted_at IS NULL", strings.TrimSpace(req.WeChatTplID)).
		First(&tpl).Error; err != nil {
		log.Printf("[Push] 查询模板失败 wechat_tpl_id=%q: %v", req.WeChatTplID, err)
		c.JSON(http.StatusNotFound, gin.H{"error": "消息模板不存在"})
		return
	}
	log.Printf("[Push] 找到模板: ID=%d, Title=%q, Platform=%q", tpl.ID, tpl.Title, tpl.Platform)

	// 3. 构建用户查询 —— 只要 role=开放推送 OR 在 user_ids 内，并且 openid 不空
	dbq := database.DB.
		Where("deleted_at IS NULL").
		Where("openid <> ''")

	// 角色过滤：空时默认“开放推送”
	roleFilter := strings.TrimSpace(req.Role)
	if roleFilter == "" {
		roleFilter = "开放推送"
	}
	dbq = dbq.Where("role = ?", roleFilter)

	// 指定 user_ids 取并集
	if len(req.UserIDs) > 0 {
		dbq = dbq.Or("user_id IN ?", req.UserIDs)
	}

	var users []models.User
	if err := dbq.Find(&users).Error; err != nil {
		log.Printf("[Push] 查询用户失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	log.Printf("[Push] 符合条件的用户数: %d", len(users))

	if len(users) == 0 {
		log.Printf("[Push] 未找到可推送用户, req=%+v", req)
		c.JSON(http.StatusNotFound, gin.H{"error": "未找到可推送的用户（请确认角色及 OpenID）"})
		return
	}

	// 4. 本地创建 Message 记录
	msg := models.Message{
		Title:       tpl.Title,
		Content:     tpl.Content,
		MessageType: tpl.MessageType,
		Platform:    tpl.Platform,
		SendTime:    time.Now(),
		Status:      "已发送",
		CreatorID:   tpl.CreatorID,
	}
	if err := database.DB.Create(&msg).Error; err != nil {
		log.Printf("[Push] 创建消息记录失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	log.Printf("[Push] 本地消息记录创建成功, message_id=%d", msg.MessageID)

	// 5. 遍历用户推送
	// … 上面查到 tpl, users, 创建 msg 记录 …

	// 5. 遍历用户推送
	var successCount, failCount int
	for _, u := range users {
		var status string

		switch strings.ToLower(tpl.Platform) {
		case "wechat":
			// 只对 wechat 调用微信接口
			err := services.SendTemplateMessage(services.TemplateMessageData{
				OpenID:     u.OpenID,
				TemplateID: tpl.WeChatTplID,
				URL:        "",
				Data: map[string]string{
					"first":  tpl.Title,
					"remark": tpl.Content,
				},
			})
			if err != nil {
				status = "推送失败: " + err.Error()
				failCount++
				log.Printf("[Push] 微信推送失败 user_id=%d, err=%v", u.ID, err)
			} else {
				status = "已推送"
				successCount++
			}

		case "web":
			// Web 平台下，你可能是往前端长轮询/WS 发消息，这里先标记已推送
			status = "已推送(web)"
			successCount++

		default:
			status = "未知平台: " + tpl.Platform
			failCount++
		}

		// 保存推送记录
		record := models.MessagePushRecord{
			MessageID:  msg.MessageID,
			UserID:     u.ID,
			Platform:   tpl.Platform,
			PushStatus: status,
			PushTime:   time.Now(),
		}
		if err := database.DB.Create(&record).Error; err != nil {
			log.Printf("[Push] 保存推送记录失败 user_id=%d: %v", u.ID, err)
		}
	}

	log.Printf("[Push] 推送完成: 成功 %d 条, 失败 %d 条", successCount, failCount)
	c.JSON(http.StatusOK, gin.H{
		"message":       "定向推送完成",
		"total_users":   len(users),
		"success_count": successCount,
		"fail_count":    failCount,
	})
}
